<template>
  <div class="user_container">
    <el-card>
      <div>
        <el-form inline>
          <el-form-item>
            <el-input placeholder="用户名" v-model="keyword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="searchHandle"
              >查询</el-button
            >
            <el-button @click="clearInpHandle">清空</el-button>
          </el-form-item>
        </el-form>
        <!-- <div class="h_10"></div> -->
        <div style="margin: 10px 0">
          <el-button type="primary" @click="addUser">添 加</el-button>
          <el-button type="danger" @click="delAllSelect">批量删除</el-button>
        </div>
        <el-table
          border
          stripe
          :data="pageList"
          @selection-change="handleSelectionChange"
          v-loading="isLoading"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />

          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="nickName" label="用户昵称" />
          <el-table-column prop="roleName" label="角色列表" width="200" />
          <el-table-column prop="gmtCreate" label="创建时间" width="180" />
          <el-table-column prop="gmtModified" label="更新时间" width="180" />

          <el-table-column
            label="操作"
            width="200"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                type="info"
                size="small"
                icon="el-icon-s-custom"
                title="分配角色"
                @click="changeRole(scope.row)"
              />
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit-outline"
                title="修改用户"
                @click="editUserInfo(scope.row)"
              />
              <el-popconfirm
                :title="`确定删除 ${scope.row.username} 吗?`"
                @confirm="delUserHandle(scope.row)"
              >
                <template #reference>
                  <el-button
                    style="margin-left: 10px"
                    type="danger"
                    size="small"
                    icon="el-icon-delete"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="paramsState.page"
          :page-size="paramsState.limit"
          :total="total"
          :page-sizes="[5, 10, 20, 30]"
          style="padding: 20px 0"
          layout="prev, pager, next, jumper, ->, sizes, total"
          @current-change="getUsers"
          @size-change="getUsers(1, $event)"
        />
      </div>

      <!-- 添加或修改角色 -->

      <el-dialog
        :title="user.id ? '修改用户' : '添加用户'"
        :visible.sync="dialogUserVisible"
        @close="cancelDia"
      >
        <el-form ref="userFormRef" :model="user" :rules="rules" label-width="120px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="user.username" />
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="user.nickName" />
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!user.id">
            <el-input v-model="user.password" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelDia">取 消</el-button>
            <el-button type="primary" @click="addorUpdateUserHandle('userFormRef')"
              >确 定</el-button
            >
          </div>
        </template>
      </el-dialog>

      <!-- 设置角色 -->
      <el-dialog
        title="设置角色"
        :visible.sync="roleState.dialogUserVisible"
        @close="cancelRole"
      >
        <el-form label-width="80px">
          <el-form-item label="用户名">
            <el-input disabled :value="roleState.user.username"></el-input>
          </el-form-item>

          <el-form-item label="角色列表">
              <!--  -->
            <el-checkbox :indeterminate="roleState.isIndeterminate"  v-model="roleState.checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0"></div>
            <el-checkbox-group v-model="roleState.userRolesIds" @change="changeCheckHandle">
              <el-checkbox :label="role.id" v-for="role in roleState.roleList" :key="role.id" >{{role.roleName}}</el-checkbox>
            </el-checkbox-group>

          </el-form-item>
        </el-form>

        <template #footer>
          <el-button type="primary" @click="onSaveRole">保存</el-button>
          <el-button @click="cancelRole">取消</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { Message } from "element-ui";
import { mapActions, mapState } from "vuex";

export default {
  name: "User",
  data() {
    return {
      isLoading:false,
      paramsState: {
        page: 1,
        limit: 5,
      },
      keyword: "",
      dialogUserVisible: false,
      user: {
        username: "",
        nickName: "",
        password: "",
      },
      ids: [],
      roleState:{
        dialogUserVisible: false,
        user:{},
        roleList:[],
        roles:[],
        userRolesIds:[],
        isIndeterminate:false,
        checkAll:false
      },
      rules:{
        username:[            
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
        ]
      }
    };
  },
  computed: {
    ...mapState({
      pageList: (state) => state.aclUser.pageList,
      total: (state) => state.aclUser.total,
      roleList :state => state.aclUser.roleList,
      roles :state => state.aclUser.roles
    }),
  },
  methods: {
    initUser() {
      return {
        username: "",
        nickName: "",
        password: "",
      };
    },

    ...mapActions("aclUser", [
      "getPageList",
      "getAddUser",
      "removeUsers",
      "removeById",
      "update",
      "getRoles",
      "getRoleList",
      "assignRoles"
    ]),
    // 分页回调
    getUsers(page, limit) {
      // 组装数据
      this.paramsState.page = page;
      if (limit) {
        this.paramsState.limit = limit;
      }
      // 发送情求
      this.getPageList(this.paramsState);
    },
    // 搜索回调
    searchHandle() {
      // 组装数据发送请求
      if (!this.keyword) {
        Message.error("输入不能为空");
      }
      const params = {
        ...this.paramsState,
        username: this.keyword,
      };
      this.getPageList(params);
    },
    // 清空回调
    clearInpHandle() {
      this.keyword = "";
      this.getPageList(this.paramsState);
    },
    // 添加回调
    addUser() {
      this.dialogUserVisible = true;
    },
    // 添加确定回调
    addorUpdateUserHandle(formName) {   
      this.$refs[formName].validate(async (valid) => {
        if (!valid) {
          Message.error('输入有误')
          return false;
        }else {
          if (this.user.id) {
            await this.update(this.user);
          } else {
            await this.getAddUser(this.user);
          }
          this.dialogUserVisible = false;
          this.paramsState.page = 1;
          this.getPageList(this.paramsState);
          this.cancelDia();
        }
      })


    },
    // 批量删除回调
    async delAllSelect() {
      await this.removeUsers(this.ids);
      this.paramsState.page = 1;
      this.getPageList(this.paramsState);
    },
    // 表格列选中回调
    handleSelectionChange(e) {
      this.ids = e.map((item) => item.id);
    },
    // 删除单个用户
    async delUserHandle(row) {
      await this.removeById(row.id);
      this.paramsState.page = 1;
      this.getPageList(this.paramsState);
    },
    // 编辑回调
    editUserInfo(row) {
      console.log(row);
      this.user.username = row.username;
      this.user.nickName = row.nickName;
      this.user.id = row.id;
      delete this.user.password;
      this.dialogUserVisible = true;
    },
    // 取消回调
    cancelDia() {
      this.user = this.initUser();
      this.dialogUserVisible = false;
    },
    // 修改角色
    async changeRole(row){
      this.roleState.dialogUserVisible = true
      this.roleState.user.username = row.username
      this.roleState.user.id = row.id
      await this.getRoles(row.id)

      this.roleState.roleList = this.roleList
      this.roleState.roles = this.roles

      this.roleState.userRolesIds = this.roles.map(item => item.id)
      this.roleState.isIndeterminate = this.roleState.userRolesIds.length > 0 && this.roleState.userRolesIds.length < this.roleState.roleList.length

    },
    // 点击多选框回调
    changeCheckHandle(e){
      this.roleState.userRolesIds = e
      this.roleState.isIndeterminate = this.roleState.userRolesIds.length > 0 && this.roleState.userRolesIds.length < this.roleState.roleList.length
      this.roleState.checkAll = this.roleState.userRolesIds.length > 0 && this.roleState.userRolesIds.length === this.roleState.roleList.length
    },
    // 全选回调
    handleCheckAllChange(e){
      this.roleState.isIndeterminate = false
      this.roleState.checkAll = e
      if(this.roleState.userRolesIds.length < this.roleState.roleList.length){
        this.roleState.userRolesIds = this.roleState.roleList.map(item => item.id)
      }else {
        this.roleState.userRolesIds = []
      }
    },
    // 取消设置角色回调
    cancelRole(){
      this.roleState.dialogUserVisible = false
      this.roleState.userRolesIds = []
    },
    // 保存角色
    async onSaveRole(){
      this.isLoading = true
      // 组装数据
      const params = {
        userId :this.roleState.user.id,
        roleId :this.roleState.userRolesIds.join(',')
      }

      // 发送请求
      await this.assignRoles(params)

      this.cancelRole()
      this.getPageList(this.paramsState)
      this.isLoading = false
    }
  },
  mounted() {
    this.getPageList(this.paramsState);
  },

};
</script>

<style scoped>
body {
  margin: 0;
}
</style>